﻿using System.Windows.Forms;
using System.Collections.Generic;
using System.IO;
using System;

namespace KiraSh.ResumeTracker
{
    public partial class frmEmailSettings : Form
    {
        private static frmEmailSettings instance = null;
        private XMLDealer xml = new XMLDealer();
        private List<EmailServer> serverList = new List<EmailServer>();
        private string path = PathHelper.MapCombine(CurrentContext.Profile.Name, "EmailServers.xml");

        public static frmEmailSettings ShowForm()
        {
            if (instance == null)
            {
                instance = new frmEmailSettings();
            }

            instance.Show();
            instance.BringToFront();

            return instance;

        }

        private frmEmailSettings()
        {
            InitializeComponent();
            this.Text = CurrentContext.Name;
        }

        private void frmEmailSettings_FormClosing(object sender, FormClosingEventArgs e)
        {
            instance = null;
        }

        private void frmEmailSettings_Load(object sender, System.EventArgs e)
        {
            PopulateCombokBox();
        }

        private void PopulateCombokBox()
        {
            this.bxEmailServers.Items.Clear();
            // populate from local folder if the file exists or copy the file to local folder if it doesn't
            if (!File.Exists(path))
            {
                xml.WriteXML(path,typeof(List<EmailServer>),EmailServer.GetDefaultList());
            }
            object o = xml.LoadXML(path, typeof(List<EmailServer>));
            
            if (o != null)
            {
                serverList = (List<EmailServer>)o;
            }

            foreach (EmailServer server in serverList)
            {
                this.bxEmailServers.Items.Add(server);
            }
        }

        private void bxName_SelectedIndexChanged(object sender, EventArgs e)
        {
            EmailServer server = (EmailServer)this.bxEmailServers.SelectedItem;
            this.bxServer.Text = server.Server;
            this.bxPort.Text = server.Port.ToString();
            this.bxPassword.Text = server.SMTPPassword;
            this.txtPasswordRepeat.Text = server.SMTPPassword;
            this.bxSMTPUsername.Text = server.SMTPUserName;
            this.bxSSL.Checked = server.SSL;
            this.bxEmail.Text = server.EmailFrom;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.ValidateChildren())
            {
                MessageBox.Show(this, "Fix all errors before saving.", "Validation Error", 
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            EmailServer server = (EmailServer)this.bxEmailServers.SelectedItem;

            if (server != null)
            {
                // save the current profile
                serverList.Remove(server);
            }
            EmailServer newServer = saveServerDetails();            
            serverList.Add(newServer);

            xml.WriteXML(path, typeof(List<EmailServer>), serverList);
            PopulateCombokBox();

            string savedNotification = "Email settings for " + newServer + " were successfully saved.";
            if (!newServer.IsFullySetup)
            {
                savedNotification += "\nThese settings cannot be used for sending emails. Information is incomplete.";
                
            }
            MessageBox.Show(this, savedNotification, "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private EmailServer saveServerDetails()
        {
            EmailServer server = new EmailServer();
            server.Name = this.bxEmailServers.Text.Trim();
            server.Port = uint.Parse(this.bxPort.Text);
            server.Server = this.bxServer.Text.Trim();
            server.SSL = this.bxSSL.Checked;
            server.SMTPPassword = this.bxPassword.Text;
            server.SMTPUserName = this.bxSMTPUsername.Text;
            server.EmailFrom = this.bxEmail.Text.Trim();

            // decided if the server ifno is complete and can be used to send emails
            if (server.Name.Length > 0
                && server.Server.Length > 0
                && server.SMTPUserName.Length > 0)
            {
                server.IsFullySetup = true;
            }
            else
            {
                server.IsFullySetup = false;
            }

            return server;
        }

        private void bxPassword_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (txtPasswordRepeat.Text == bxPassword.Text)
            {
                errorPasswordProvider.Clear();
            }
            else
            {
                errorPasswordProvider.SetError((Control)txtPasswordRepeat, "Passwords do not match");
                errorPasswordProvider.SetError((Control)bxPassword, "Passwords do not match");
                e.Cancel = true;
            }
        }

        private void bxPort_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            uint portNum;
            if (uint.TryParse(bxPort.Text, out portNum))
            {
                errorPortProvider.Clear();
            }
            else
            {
                errorPortProvider.SetError((Control)sender, "Port must be a number");
                e.Cancel = true;
            }
        }

        private void required_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (((Control)sender).Text.Trim().Length == 0)
            {
                e.Cancel = true;
                errorRequiredProvider.SetError((Control)sender, "Required field");
            }
            else
            {
                errorRequiredProvider.SetError((Control)sender, "");
            }
        }
    }
}
